package com.itheima.utils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/*
    作为servlet的一个基础处理类


 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.获取请求的URI
        String requestURI = req.getRequestURI();
        System.out.println("uri"+requestURI);

        //2.截取uri中最后的内容(方法名)作为被执行的方法名
        String methodName = requestURI.substring(requestURI.indexOf("/") + 1);
        System.out.println(methodName);

        //3.method对象
        //3.1 执行的类对象
        try {
            //3.2  获取执行的方法对象
            Method method = this.getClass().getDeclaredMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);
            //暴力反射 获取所有私有方法
            method.setAccessible(true);
            //3.3执行目标方法
            method.invoke(this,req,resp);  //执行this对象上带有req和resp参数的method方法



        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
